package com.hanklee.demo

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.hanklee.demo.utils.RTSTWebSocketListener
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft

import org.java_websocket.handshake.ServerHandshake
import java.io.UnsupportedEncodingException
import java.net.URI
import java.nio.ByteBuffer
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class RTSTWebSocketClient(
    serverUri: URI,
    protocolDraft: Draft?,
    private val listener: RTSTWebSocketListener
) :
    WebSocketClient(serverUri, protocolDraft) {

    init {
        if (serverUri.toString().contains("wss")) {
            trustAllHosts(this)
        }
    }

    override fun onOpen(handshake: ServerHandshake) {
        listener.onOpen(handshake)
    }

    private val TAG = RTSTWebSocketClient::class.java.simpleName

    override fun onMessage(msg: String) {
        val msgObj: JSONObject = JSON.parseObject(msg)
        when (val action: String = msgObj.getString("action")) {
            "started" -> {
                // 握手成功
                listener.onMessage(action, msg)
            }

            "result" -> {
                // 转写结果
                listener.onMessage(action, getContent(msgObj.getString("data")))
            }

            "error" -> {
                // 连接发生错误
                listener.onMessage(action, msg)
            }
        }
    }

    override fun onError(e: java.lang.Exception) {
        listener.onError(e)
    }

    override fun onClose(arg0: Int, arg1: String, arg2: Boolean) {
        listener.onClose(arg0, arg1, arg2)
    }

    override fun onMessage(bytes: ByteBuffer) {
        try {

        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
    }

    private fun trustAllHosts(appClient: RTSTWebSocketClient) {
        println("wss")
        val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
            override fun getAcceptedIssuers(): Array<X509Certificate> {
                return arrayOf()
            }

            @Throws(CertificateException::class)
            override fun checkClientTrusted(arg0: Array<X509Certificate?>?, arg1: String?) {
                // TODO Auto-generated method stub
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(arg0: Array<X509Certificate?>?, arg1: String?) {
                // TODO Auto-generated method stub
            }
        })
        try {
            val sc = SSLContext.getInstance("TLS")
            sc.init(null, trustAllCerts, SecureRandom())
            appClient.socket = sc.socketFactory.createSocket()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    // 把转写结果解析为句子
    private fun getContent(message: String?): String {
        val resultBuilder = StringBuffer()
        try {
            val messageObj: JSONObject = JSON.parseObject(message)
            val cn: JSONObject = messageObj.getJSONObject("cn")
            val st: JSONObject = cn.getJSONObject("st")
            val type: String = st.getString("type")
            if (type == "0") {
                val rtArr: JSONArray = st.getJSONArray("rt")
                for (i in 0 until rtArr.size) {
                    val rtArrObj: JSONObject = rtArr.getJSONObject(i)
                    val wsArr: JSONArray = rtArrObj.getJSONArray("ws")
                    for (j in 0 until wsArr.size) {
                        val wsArrObj: JSONObject = wsArr.getJSONObject(j)
                        val cwArr: JSONArray = wsArrObj.getJSONArray("cw")
                        for (k in 0 until cwArr.size) {
                            val cwArrObj: JSONObject = cwArr.getJSONObject(k)
                            val wStr: String = cwArrObj.getString("w")
                            resultBuilder.append(wStr)
                        }
                    }
                }
            }
        } catch (e: java.lang.Exception) {
            return resultBuilder.toString()
        }
        return resultBuilder.toString()
    }
}
